package com.daijt.mobile.service.hibernate;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.stereotype.Service;

import com.daijt.mobile.persistence.ListItem;
import com.daijt.mobile.service.ListItemService;

@Service
public class ListItemServiceImpl extends JpaDaoSupport implements
		ListItemService {

	private final String DELETE_LIST_ITEMS = "delete from ListItem li where li.listId = :listId";
	
	private final String REMOVE_DELETED_ITEMS = "delete from ListItem li where li.listId = :listId and li.id not in :idset";
	
	@Autowired
	@Required
	public void setJpaEntityManagerFactory(
	        @Qualifier("entityManagerFactory")EntityManagerFactory entityManagerFactory) {
		super.setEntityManagerFactory(entityManagerFactory);
	}
	
	public void insertListItems(List<ListItem> items) {
		for (ListItem item : items) {
			getJpaTemplate().persist(item);
		}
		
	
		getJpaTemplate().flush();
	}

	public void clearItemsFromList(final long listId) {
		@SuppressWarnings("unused")
		Integer reuslt = getJpaTemplate().execute(new JpaCallback<Integer>(){

			public Integer doInJpa(EntityManager em)
					throws PersistenceException {
				Query query = em.createQuery(DELETE_LIST_ITEMS);
				query.setParameter("listId", listId);
				int rs = query.executeUpdate();
				return rs;
			}
			
		});
		
		getJpaTemplate().flush();
	}

	public void mergeListItems(final long listId, List<ListItem> items) {
		final Set<Long> idSet = new HashSet<Long>();
		
		getJpaTemplate().flush();
		
		// Insert or update items
		for (ListItem item : items) {
			
			idSet.add(item.getId());
			getJpaTemplate().merge(item);
		}
		
		// Delete
		@SuppressWarnings("unused")
		Integer reuslt = getJpaTemplate().execute(new JpaCallback<Integer>(){

			public Integer doInJpa(EntityManager em)
					throws PersistenceException {
				Query query = em.createQuery(REMOVE_DELETED_ITEMS);
				query.setParameter("listId", listId);
				query.setParameter("idset", idSet);
				int rs = query.executeUpdate();
				return rs;
			}
			
		});
		
	
		getJpaTemplate().flush();
		
	}

}
